import { AtForm, AtInput, AtButton, AtMessage } from 'taro-ui'
import React, { useEffect, useState } from 'react'
import { userDetail, userLogin } from '@/api/user';
import { BaseEventOrig, CommonEventFunction } from '@tarojs/components/types/common'
import { Button, ButtonProps, Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useUserStore } from '@/store';

const Login: React.FC = () => {
  const userStore = useUserStore();

  const [avatar, setAvatar] = useState<string>('');
  const [username, setUsername] = useState<string>('');
  const [password, setPassword] = useState<string>('');

  const [phoneCode, setPhoneCode] = useState<string>("");

  const handleChangeUsername = (val: string) => setUsername(val);
  const handleChangePassword = (val: string) => setPassword(val);

  const onChooseAvatar = async (e: BaseEventOrig<{ avatarUrl: string }>) => {
    const { avatarUrl } = e.detail;
    const { data } = await Taro.uploadFile({ url: "http://127.0.0.1:8080/user/upload", filePath: avatarUrl, name: 'avatar' });
    setAvatar(data);
  }

  const getPhoneNumber: CommonEventFunction<ButtonProps.onGetPhoneNumberEventDetail> = (e) => {
    const { code } = e.detail;
    setPhoneCode(code!);
  }


  useEffect(() => {
    const fetchUserInfo = async () => {
      if (userStore.token) {
        const { data: user } = await userDetail();
        userStore.setUsername(user.username);
        userStore.setAvatar(user.avatar);
        userStore.setGender(user.gender);
        userStore.setRole(user.role);
        userStore.setAddressList(user.addressList);
        userStore.setBalance(user.balance);

        if (user.role === "user") {
          Taro.switchTab({ url: "/pages/index/index" });
        } else {
          Taro.switchTab({ url: "/pages/employee/order/index" });
        }
      }
    }

    fetchUserInfo();
  }, [userStore.token])

  const onSubmit = async () => {
    const { code } = await Taro.login();
    const data = await userLogin({ username, password, code, avatar, phoneCode });
    if (data.code === 200) {
      userStore.setToken(data.data);
      Taro.atMessage({
        type: "success",
        message: "登陆成功"
      })
    } else {
      Taro.atMessage({
        type: "error",
        message: "登陆失败，请重试"
      })
    }
  }

  const onReset = () => {
    setUsername("");
    setPassword("");
  }

  return (
    <>
      <AtMessage />
      <View className='h-screen flex items-center justify-center'>
        <AtForm
          onSubmit={onSubmit}
          onReset={onReset}
        >
          <Button openType='chooseAvatar' onChooseAvatar={(e) => onChooseAvatar(e)} className='p-0 m-0 border-none bg-transparent'>
            <Image src={avatar} className='w-20 h-20 rounded-full' />
          </Button>
          <AtInput
            name='email'
            title='用户名'
            type='nickname'
            placeholder='请输入用户名'
            value={username}
            onChange={handleChangeUsername}
            className='mb-3'
          />
          <AtInput
            name='password'
            title='密码'
            type='password'
            placeholder='请输入密码'
            value={password}
            onChange={handleChangePassword}
            className='mb-3'
          />
          <AtButton openType='getPhoneNumber' onGetPhoneNumber={getPhoneNumber}>同意</AtButton>

          <AtButton formType='submit' type='primary'>提交</AtButton>
          <AtButton formType='reset'>重置</AtButton>
        </AtForm>
      </View>
    </>
  )
}

export default Login;
